package cn.edu.zjicm.wordsnet_d.fragment;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import cn.edu.zjicm.wordsnet_d.R;
import cn.edu.zjicm.wordsnet_d.activity.DataToRestActivity;
import cn.edu.zjicm.wordsnet_d.activity.WordDetailActivity;
import cn.edu.zjicm.wordsnet_d.data.DataManager;
import cn.edu.zjicm.wordsnet_d.data.OneWord;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference;
import cn.edu.zjicm.wordsnet_d.datapersistent.FileManager;
import cn.edu.zjicm.wordsnet_d.media.VoicePlayer;
import cn.edu.zjicm.wordsnet_d.util.NightModeUtil;
import cn.edu.zjicm.wordsnet_d.util.TypefaceUtil;
import cn.edu.zjicm.wordsnet_d.view.WriteView;

public class WordDetailFragment extends Fragment {

	public WordDetailFragment(OneWord word) {
		this.mOneWord = word;
	}

	public WordDetailFragment() {

	}

	private static final String BUNDLE_KEY_WORD_DETAIL = "bundle_key_word_detail";
	// Data
	private OneWord mOneWord;
	private boolean forSearchView = false; // 是否用于搜索界面

	// View
	private ViewFlipper mWriteFlipper;
	private ScrollView mScrollView, affixDisplayView;
	private LinearLayout mFakeScrollView;
	private TextView mWordText;
	private TextView mWordPhonetic;
	private TextView mWordAff;
	private TextView cetTest;
	// 右上角按钮
	private ImageView mReadButton;
	private Button mAddButton;
	// popup window
	private PopupWindow mWriteWindow;
	private WriteView mWriteView;
	private View v;
	private RelativeLayout playLemma;
	private int buttonDrawable[];

	private FragmentManager fragmentManager;
	private FragmentTransaction ft;
	private Fragment wordInnerFragment;

	private boolean hasShowSyllable = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		v = inflater.inflate(R.layout.fragment_word_detail_for_search, null);

		mWriteFlipper = (ViewFlipper) v.findViewById(R.id.write_flipper);
		mScrollView = (ScrollView) v.findViewById(R.id.word_detail_scroll_view);
		mFakeScrollView = (LinearLayout) v.findViewById(R.id.fake_scroll_view);
		mWordText = (TextView) v.findViewById(R.id.word_detail_word);

		mWordPhonetic = (TextView) v.findViewById(R.id.word_detail_phonetic);
		TypefaceUtil.getInstance(getActivity()).setTypeface(mWordPhonetic);

		mReadButton = (ImageView) v.findViewById(R.id.read_button);

		mAddButton = (Button) v.findViewById(R.id.add_button);
		cetTest = (TextView) v.findViewById(R.id.cet_test);

		playLemma = (RelativeLayout) v.findViewById(R.id.play_sound);

		if (forSearchView) {
			cetTest.setVisibility(View.VISIBLE);
		} else {
			mAddButton.setVisibility(View.GONE);
		}

		forSearchView = false;
		if (mOneWord != null)
			initView();
		buttonDrawable = new int[2];
		if (NightModeUtil.isNightModeNow()) {
			buttonDrawable[0] = R.drawable.rectangle_green_button;
			buttonDrawable[1] = R.drawable.rectangle_gray_button;
		} else {
			buttonDrawable[0] = R.drawable.green_button_unclicked;
			buttonDrawable[1] = R.drawable.gray_button_unclicked;
		}
		return v;
	}

	private void setCet(int bookId) {
		if (bookId == 0) {
			cetTest.setText("低频单词");
		} else if (bookId == AppPreference.Book.BOOK_ID[6]) {
			cetTest.setText("高中单词");
		} else if (bookId == AppPreference.Book.BOOK_ID[0]) {
			cetTest.setText("四级单词");
		} else if (bookId == AppPreference.Book.BOOK_ID[1]) {
			cetTest.setText("六级单词");
		} else if (bookId == AppPreference.Book.BOOK_ID[2]) {
			cetTest.setText("考研单词");
		} else if (bookId == AppPreference.Book.BOOK_ID[0] + AppPreference.Book.BOOK_ID[1]) {
			cetTest.setText("四级,六级单词");
		} else if (bookId == AppPreference.Book.BOOK_ID[0] + AppPreference.Book.BOOK_ID[2]) {
			cetTest.setText("四级,考研单词");
		} else if (bookId == AppPreference.Book.BOOK_ID[1] + AppPreference.Book.BOOK_ID[2]) {
			cetTest.setText("六级,考研单词");
		} else if (bookId == AppPreference.Book.BOOK_ID[0] + AppPreference.Book.BOOK_ID[1] + AppPreference.Book.BOOK_ID[2]) {
			cetTest.setText("四级,六级,考研单词");
		} else {
			cetTest.setText("");
		}
	}

	public void initViewForNewWord(OneWord word) {
		this.mOneWord = word;
		initView();
	}

	private void initView() {
		hasShowSyllable = false;

		String str = mOneWord.getLemma();
		// str = str + mOneWord.getSyllableCount();
		// for(int i = 0; i < mOneWord.getSyllableCount(); i++)
		// str = str + " " + mOneWord.getSyllables()[i];
		mWordText.setText(str);
		mWordPhonetic.setText(mOneWord.getPhonetic());

		fragmentManager = getChildFragmentManager();
		ft = fragmentManager.beginTransaction();
		wordInnerFragment = fragmentManager.findFragmentByTag("wordDetail"); // 判断这个fragment是否存在

		if (wordInnerFragment == null) {
			wordInnerFragment = new WordInnerFragment(mOneWord, false, false);
			ft.add(R.id.word_inner_fragment, wordInnerFragment, "wordDetail").commit();
		} else {
			wordInnerFragment = new WordInnerFragment(mOneWord, false, false);
			ft.replace(R.id.word_inner_fragment, wordInnerFragment, "wordDetail").commit();
		}

		if (FileManager.isVoiceFileExist(getActivity(), mOneWord)) {
			showReadIcon();
		} else {
			removeReadIcon();
		}

		mWriteWindow = null;

		if (FileManager.isVoiceFileExist(getActivity(), mOneWord)) {
			mReadButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					VoicePlayer.getInstance(getActivity()).playWithNoCheckVoiceFile(mOneWord);
					if (!hasShowSyllable) {
						mWordText.setText(mOneWord.getSyllablesSpan(getActivity()));
						hasShowSyllable = true;
					}
				}
			});
			playLemma.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					VoicePlayer.getInstance(getActivity()).play(mOneWord);
					if (!hasShowSyllable) {
						mWordText.setText(mOneWord.getSyllablesSpan(getActivity()));
						hasShowSyllable = true;
					}
				}
			});
		} else {
			removeReadIcon();
		}

		cetTest.setText(mOneWord.getBookName());

	}

	private void showReadIcon() {
		mReadButton.setVisibility(View.VISIBLE);
	}

	// 隐藏发音图标
	void removeReadIcon() {
		mReadButton.setVisibility(View.GONE);
	}

	public void showAddButton() {
		if (mOneWord.getDegree() == OneWord.DEGREE_UNFAMILIAR && mOneWord.getSense_degree_fm() > 0) {
			// 如果是生词，显示“设为熟词”
			mAddButton.setVisibility(View.VISIBLE);
			mAddButton.setText("设为熟词");
			mAddButton.setTextColor(Color.BLACK);
			mAddButton.setBackgroundResource(buttonDrawable[1]);
			mAddButton.setOnClickListener(mSetToFamiliarListener);
		} else if (mOneWord.getDegree() == OneWord.DEGREE_FAMILIAR) {
			// 如果是熟词或太简单，显示“设为生词”
			mAddButton.setVisibility(View.VISIBLE);
			mAddButton.setText("设为生词");
			mAddButton.setTextColor(Color.WHITE);
			mAddButton.setBackgroundResource(buttonDrawable[0]);
			mAddButton.setOnClickListener(mSetToUnFamiliarListener);
		} else if (mOneWord.getDegree() == OneWord.DEGREE_UNLEARN || (mOneWord.getDegree() == OneWord.DEGREE_UNFAMILIAR && mOneWord.getSense_degree_fm() == 0)) {
			// 如果是未学单词或待学单词，显示“设为生词”，设为生词后，显示“移出生词本”可重新设为未学单词
			mAddButton.setVisibility(View.VISIBLE);
			mAddButton.setText("设为生词");
			mAddButton.setTextColor(Color.WHITE);
			mAddButton.setBackgroundResource(buttonDrawable[0]);
			mAddButton.setOnClickListener(mSetToUnFamiliarListener);
		}
		DataToRestActivity.getInstance().setDBChanged(true);
	}

	OnClickListener mSetToUnFamiliarListener = new OnClickListener() {
		@Override
		public void onClick(View arg0) {

			OneWord w = DataManager.getInstance().findWord(mOneWord, getActivity());
			boolean unlearn = w == null || w.getDegree() == OneWord.DEGREE_UNLEARN;
			boolean tooEasy = w != null && w.getDegree_fm() == OneWord.DEGREE_FAMILIAR && w.getSense_degree_fm() == OneWord.SENSE_DEGREE_TOO_EASY;
			if (w == null)
				DataManager.getInstance().changeUnLearnToUnFamiliar(mOneWord, getActivity(), true);
			else if (w.getDegree_fm() == OneWord.DEGREE_FAMILIAR && w.getSense_degree_fm() < OneWord.SENSE_DEGREE_TOO_EASY)
				DataManager.getInstance().changeFamiliarToUnFamiliar(w, getActivity());
			else if (w.getDegree_fm() == OneWord.DEGREE_FAMILIAR && w.getSense_degree_fm() == OneWord.SENSE_DEGREE_TOO_EASY)
				DataManager.getInstance().changeTooEasyToUnFamiliar(w, getActivity());
			if (w != null)
				mOneWord = w;
			Toast.makeText(getActivity(), mOneWord.getLemma() + "已添加到学习队列", Toast.LENGTH_SHORT).show();
			mAddButton.setVisibility(View.VISIBLE);
			mAddButton.setTextColor(Color.BLACK);
			mAddButton.setBackgroundResource(buttonDrawable[1]);
			if (unlearn) {
				mAddButton.setVisibility(View.GONE); // 这里去掉移除生词本 add by ct
				// mAddButton.setText("移出生词本");
				// mAddButton.setOnClickListener(mSetToUnlearnListener);
			} else if (tooEasy) {
				mAddButton.setVisibility(View.VISIBLE);
				mAddButton.setText("设为太简单");
				mAddButton.setOnClickListener(mSetToTooEasyListener);
			} else {
				mAddButton.setVisibility(View.VISIBLE);
				mAddButton.setText("设为熟词");
				mAddButton.setOnClickListener(mSetToFamiliarListener);
			}
		}
	};

	OnClickListener mSetToFamiliarListener = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			AlertDialog.Builder builder = new Builder(getActivity());
			builder.setMessage("是否将" + mOneWord.getLemma() + "设为熟词？");
			builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					OneWord w = DataManager.getInstance().findWord(mOneWord, getActivity());
					DataManager.getInstance().changeUnFamiliarToFamiliar(w, getActivity());
					if (w != null)
						mOneWord = w;
					Toast.makeText(getActivity(), mOneWord.getLemma() + "已设为熟词", Toast.LENGTH_SHORT).show();
					// mAddButton.setBackgroundResource(R.drawable.added_ico);
					mAddButton.setVisibility(View.VISIBLE);
					mAddButton.setText("添加到学习队列");
					mAddButton.setTextColor(Color.WHITE);
					mAddButton.setBackgroundResource(buttonDrawable[0]);
					mAddButton.setOnClickListener(mSetToUnFamiliarListener);
				}
			});
			builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
			builder.create().show();
		}
	};

	OnClickListener mSetToTooEasyListener = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			AlertDialog.Builder builder = new Builder(getActivity());
			builder.setMessage("是否将" + mOneWord.getLemma() + "设为太简单？");
			builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					OneWord w = DataManager.getInstance().findWord(mOneWord, getActivity());
					DataManager.getInstance().changeUnFamiliarToTooEasy(w, getActivity());
					if (w != null)
						mOneWord = w;
					Toast.makeText(getActivity(), mOneWord.getLemma() + "已设为太简单", Toast.LENGTH_SHORT).show();
					// mAddButton.setBackgroundResource(R.drawable.added_ico);
					mAddButton.setVisibility(View.VISIBLE);
					mAddButton.setText("设为生词");
					mAddButton.setTextColor(Color.WHITE);
					mAddButton.setBackgroundResource(buttonDrawable[0]);
					mAddButton.setOnClickListener(mSetToUnFamiliarListener);
				}
			});
			builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
			builder.create().show();
		}
	};

	OnClickListener mSetToUnlearnListener = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			AlertDialog.Builder builder = new Builder(getActivity());
			builder.setMessage("是否将" + mOneWord.getLemma() + "移出生词本？");
			builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					OneWord w = DataManager.getInstance().findWord(mOneWord, getActivity());
					DataManager.getInstance().changeUnFamiliarToUnLearn(w, getActivity());
					if (w != null)
						mOneWord = w;
					Toast.makeText(getActivity(), mOneWord.getLemma() + "已移出生词本", Toast.LENGTH_SHORT).show();
					// mAddButton.setBackgroundResource(R.drawable.added_ico);
					mAddButton.setVisibility(View.VISIBLE);
					mAddButton.setText("添加到学习队列");
					mAddButton.setTextColor(Color.WHITE);
					mAddButton.setBackgroundResource(buttonDrawable[0]);
					mAddButton.setOnClickListener(mSetToUnFamiliarListener);
				}
			});
			builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
			builder.create().show();
		}
	};

	public void displayDetailView() {
		if (getActivity() instanceof WordDetailActivity) {
			((WordDetailActivity) getActivity()).setTitleText(mOneWord.getLemma());
		}
		mWriteFlipper.setDisplayedChild(0);
	}

	public boolean isWriteViewShowing() {
		return mWriteFlipper.getDisplayedChild() == 1;
	}

	public void setForSearchView(Boolean in) {
		forSearchView = in;
	}

}